import time

import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

# 设置颜色
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# 设置蛇的初始位置和速度
snake_pos = [100, 50]
snake_speed = [10, 0]

# 蛇身体列表，用于存储蛇的每个部分的位置
snake_body = [[100, 50]]

# 设置食物的初始位置
food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]

# 设置得分
score = 0

# 设置游戏窗口和时钟
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

# 游戏结束函数
def game_over():
    my_font = pygame.font.SysFont('times new roman', 90)
    game_over_surface = my_font.render('game over', True, RED)
    game_over_rect = game_over_surface.get_rect()
    game_over_rect.midtop = (SCREEN_WIDTH/2, SCREEN_HEIGHT/4)
    screen.fill(WHITE)
    screen.blit(game_over_surface, game_over_rect)
    pygame.display.flip()

    time.sleep(2)
    pygame.quit()
    sys.exit()

# 主游戏循环
while True:
    # 检查按键事件
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and snake_speed[1] != 10:
                snake_speed = [0, -10]
            if event.key == pygame.K_DOWN and snake_speed[1] != -10:
                snake_speed = [0, 10]
            if event.key == pygame.K_LEFT and snake_speed[0] != 10:
                snake_speed = [-10, 0]
            if event.key == pygame.K_RIGHT and snake_speed[0] != -10:
                snake_speed = [10, 0]
        if event.type == pygame.QUIT:
            game_over()

    # 更新蛇的位置
    snake_pos[0] += snake_speed[0]
    snake_pos[1] += snake_speed[1]

    # 蛇吃到食物
    if snake_pos == food_pos:
        score += 1
        food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]
    else:
        snake_body.pop(0)  # 移除蛇的尾部

    # 蛇身体增长
    snake_body.append(snake_pos[:])

    # 填充背景颜色
    screen.fill(WHITE)

    # 画蛇
    for pos in snake_body:
        pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))

    # 画食物
    pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    # 显示得分
    score_font = pygame.font.SysFont('times new roman', 35)
    score_surface = score_font.render('score: ' + str(score), True, BLACK)
    screen.blit(score_surface, (10, 10))

    # 检查蛇是否撞到墙壁或自己的身体
    if snake_pos[0] < 0 or snake_pos[0] > SCREEN_WIDTH-10:
        game_over()
    if snake_pos[1] < 0 or snake_pos[1] > SCREEN_HEIGHT-10:
        game_over()
    for block in snake_body[:-1]:
        if snake_pos == block:
            game_over()

    # 更新屏幕显示
    pygame.display.update()

    # 控制游戏帧率
    clock.tick(15)